<template>
  <div class="container">
    <div class="top">
      <div class="top-left">
        <span class="top-left-title">文章标题：</span>
        <el-input v-model="articleForm.title" style="width: 300px;" placeholder="请输入文章标题" />
      </div>
      <div class="top-right">
        <el-upload
          ref="upload"
          class="upload-demo"
          :limit="1"
          :on-exceed="handleExceed"
          :auto-upload="false"
          :on-change="handleChange"
        >
          <template #trigger>
            <el-button type="primary">选择文章封面，否则自动生成</el-button>
          </template>
          <el-button style="margin-left: 20px;" class="ml-3" type="success" @click="submitUpload">
            上传封面到服务器
          </el-button>
          <template #tip>
            <div class="el-upload__tip text-red">
              限制1个文件，新文件将覆盖旧文件
            </div>
          </template>
        </el-upload>
      </div>
    </div>
    <div class="center">
      <span class="center-title">文章简介：</span>
      <el-input
        v-model="articleForm.introduce"
        style="width: 100%"
        :rows="5"
        type="textarea"
        placeholder="请输入对应简介，若用户不输入则默认生成"
        :style="{ '--el-input-border-radius': '0' }" 
      />
    </div>
    <div class="bottom">
      <div class="bottom-top">
        <div class="bottom-top-title">文章内容: </div>
        <v-md-editor
            height="600px"
            v-model="articleForm.content"
            :disabled-menus="[]"
            @upload-image="handleUploadImage"
        ></v-md-editor>
      </div>
      <div class="bottom-bottom">
        <el-button type="primary" @click="submitAnArticle">提交文章</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRoute } from 'vue-router';
import {ref, reactive} from 'vue';
import { genFileId, ElMessage } from 'element-plus'
import type { UploadInstance, UploadFile, UploadRawFile } from 'element-plus'
import {fileApi} from '@/api/file.js'
import {articleApi} from '@/api/article.js'

//### 变量定义 ###
const route = useRoute();  //路由变量
const articleForm = reactive({  //文章变量表单
  id: "-1",
  title: "",
  cover: "",
  content: "",
  introduce: ""
})

//### 方法定义 ###
const pageInitialization = async () => {
  const routerId = Array.isArray(route.query.articleId) 
    ? route.query.articleId[0]  // 如果是数组，取第一个元素
    : route.query.articleId;    // 否则直接使用
  articleForm.id = routerId || '-1';
  
  if("-1" === articleForm.id || "" === articleForm.id || articleForm.id === undefined) { //说明是文章新增
    return;
  }else { //说明是文章修改
    const result = await articleApi.getByIdArticle({"id":articleForm.id});
    if(result.code === 200) {
      Object.assign(articleForm, result.data);
    }
  }
}

//### 初始化调用 ###
pageInitialization();

//封面操作开始 
// 文件超出限制时的处理
const upload = ref<UploadInstance>()
let selectedFile: UploadRawFile | null = null // 存储选中的文件
 
// 文件超出限制时的处理
const handleExceed: (files: UploadRawFile[]) => void = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
  selectedFile = file // 保存选中的文件
}
 
// 文件变化时触发
const handleChange: (file: UploadFile, fileList: UploadFile[]) => void = (file, _) => {
  selectedFile = file.raw as UploadRawFile // 保存选中的文件
  // console.log('当前选择的文件', selectedFile);
}
 
// 手动上传文件
const submitUpload = async () => {
  if (!selectedFile) {
    console.error('No file selected')
    return
  }
 
  let formData = new FormData();
  formData.append('filedata', selectedFile) // 添加文件到 FormData
  const result = await fileApi.uploadFile(formData);
  if(result.code === 200) {
    ElMessage({
      message: '文章封面上传成功！',
      type: 'success',
      plain: true,
    })
    articleForm.cover = result.data.fileRelativePath;
  }else {
    ElMessage({
      message: '文章封面上传失败',
      type: 'error',
      plain: true,
    })
  }
}
//封面操作结束

//内容绑定方法开始
const handleUploadImage =  async (event:any, insertImage:any, files:any) => {
  console.log('文章中上传文件方法被触发');
    if (files && files.length > 0) {
    const formData = new FormData();
    formData.append("filedata", files[0]);
    const res = await fileApi.uploadFile(formData);
    console.log("上传图片输出结果：", res.data);

    if (res.code == 200) {
      // 此处只做示例
      insertImage({
        url: res.data.fileRelativePath
      });
      ElMessage({
        type: "success",
        message: "图片上传成功",
      });
    } else {
      ElMessage({
        type: "error",
        message: "图片上传失败",
      });
    }
  } else {
    ElMessage({
      type: "error",
      message: "没有选择对应文件",
    });
  }
};
//内容绑定方法结束

//文章上传方法开始
const submitAnArticle = async () => {
  if(articleForm.id == "-1") {  //说明是新增
    const { id, ...data } = articleForm;  //排除id
    const result = await articleApi.addArticle(data);
    if(result.code === 200) {
      //恢复
      articleForm.id = "-1";
      articleForm.title = "";
      articleForm.cover = "";
      articleForm.content = "";
      articleForm.introduce = "";
      ElMessage({
        message: result.data.message,
        type: 'success',
        plain: true,
      })
    }else {
      ElMessage({
        message: '文章上传失败',
        type: 'error',
        plain: true,
      })
    }
  }else { //说明是修改文章
    const result = await articleApi.updateArticle(articleForm);
    if(result.code === 200) {
      //恢复
      articleForm.id = "-1";
      articleForm.title = "";
      articleForm.cover = "";
      articleForm.content = "";
      articleForm.introduce = "";
      ElMessage({
        message: result.data.message,
        type: 'success',
        plain: true,
      })
    }else {
      ElMessage({
        message: '文章修改失败',
        type: 'error',
        plain: true,
      })
    }
  }
}
//文章上传方法结束
</script>

<style scoped lang="scss">
.container {
  display: flex;
  flex-direction: column;
  height: 85vh;       /* 固定高度 */
  overflow: auto;      /* 整体滚动 */
  // background: red;

  /* 关键：允许子项收缩 */
  > * {
    min-height: 0;     /* 覆盖 Flex 默认的 min-height: auto */
  }

  .top {
    flex-shrink: 0;    /* 固定高度（不拉伸） */
    // background: green;
    display: flex;

    .top-left {
      flex: 5;
      display: flex;
      align-items: center; /* 副轴居中 */

      .top-left-title {
        font-weight: bold;
      }
    }

    .top-right {
      flex: 5;
      align-items: center; /* 副轴居中 */
      display: grid;
      place-items: center; /* 同时水平和垂直居中 */
    }
  }

  .center {
    flex-shrink: 0;    /* 固定高度 */
    // background: hotpink;
    margin-top: 10px;

    .center-title {
      font-weight: bold;
    }
  }

  .bottom {
    flex: 1;           /* 占满剩余空间 */
    // background: indianred;
    display: flex;
    flex-direction: column;

    .bottom-top {

      .bottom-top-title {
        font-weight: bold;
      }
    }

    .bottom-bottom {
      text-align: right;
      margin-right: 30px;
      margin-top: 10px;
    }
  }
}

// 备份无法滑动整体版本
// .container {
//   display: flex;
//   flex-direction: column;
//   height: 85vh;
//   background: red;
//   overflow: auto;

//   .top {
//     background: green;
//     display: flex;

//     .top-left {
//       flex: 5;
//       display: flex;
//       align-items: center; /* 副轴居中 */

//       .top-left-title {
//         font-weight: bold;
//       }
//     }

//     .top-right {
//       flex: 5;
//       align-items: center; /* 副轴居中 */
//       display: grid;
//       place-items: center; /* 同时水平和垂直居中 */
//     }
//   }

//   .center {
//     background: hotpink;
//     margin-top: 10px;

//     .center-title {
//       font-weight: bold;
//     }
//   }

//   .bottom {
//     background: indianred;
//     .bottom-top {

//       .bottom-top-title {
//         font-weight: bold;
//       }
//     }

//     .bottom-bottom {
//       text-align: right;
//       margin-right: 30px;
//     }
//   }
// }
</style>
